package com.yc.hwc.biz;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;

import com.yc.jpa.bean.PageBean;

@Transactional(rollbackFor = BizException.class)
public abstract class BaseBiz<E> {

	protected JpaRepository<E, Long> dao;

	/**
	 * 子类必须加 @Resource 或 @Autowired 注解
	 */
	@Autowired
	public void setDao(JpaRepository<E, Long> dao) {
		this.dao = dao;
	}

	public JpaRepository<E, Long> getDao() {
		return dao;
	}

	public E get(Long id) {
		return dao.findById(id).get();
	}

	public Page<E> find() {
		return find(null, PageBean.defaultPage());
	}

	public Page<E> find(E e) {
		return find(e, PageBean.defaultPage());
	}

	public Page<E> find(E e, PageBean page) {
		return e == null ? dao.findAll(page.build()) : dao.findAll(Example.of(e), page.build());
	}

	public E save(E e, Errors es) throws BizException {
		try {
			if (validate(e, es)) {
				return dao.save(e);
			} else {
				return null;
			}
		} catch (RuntimeException ex) {
			throw new BizException("业务繁忙，请稍后再试！", ex);
		}
	}

	/**
	 * 自定义业务逻辑，默认做字段验证，返回false表示不执行默认的保存方法
	 */
	protected boolean validate(E e, Errors es) throws BizException {
		if (es != null && es.hasErrors()) {
			throw new BizException("提交数据错误", -1, es.getAllErrors());
		}
		return true;
	}

	public void del(Long id) throws BizException {
		try {
			dao.deleteById(id);
		} catch (RuntimeException ex) {
			throw new BizException("业务繁忙，请稍后再试！", ex);
		}

	}

	public void del(E e) {
		dao.delete(e);
	}

}
